package com.topisv.tms.utils.bsht;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXB;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.ExpressConfigure;
import com.topisv.tms.entity.WarehouseAddress;
import com.topisv.tms.task.interfacetask.SelfException;
import com.topisv.tms.utils.aop.AopLogs;
import com.topisv.tms.utils.bsht.vo.BillCancelResponse;
import com.topisv.tms.utils.bsht.vo.BillPrintDeliveryCancel;
import com.topisv.tms.utils.bsht.vo.BillPrintDeliveryRequest;
import com.topisv.tms.utils.bsht.vo.BillPrintDeliveryResponse;
import com.topisv.tms.utils.bsht.vo.BillPrintDetailRsp;
import com.topisv.tms.utils.bsht.vo.BillPrintRequest;
import com.topisv.tms.utils.bsht.vo.BillPrintResponse;
import com.topisv.tms.utils.bsht.vo.CreatePrintFeedBack;
import com.topisv.tms.utils.bsht.vo.EDIPrintDetail;
import com.topisv.tms.utils.bsht.vo.RemovePrintFeedBack;
import com.topisv.tms.utils.sf.Util;

public class MailBSHTUtil {
	private static final Logger log = LoggerFactory.getLogger(AopLogs.class);
	
	private static String serviceType_Request = "BillPrintRequest";	//请求电子面单接口
	private static String serviceType_Back = "BillPrintDeliveryRequest";	//发货反馈接口
	private static String serviceType_Cancel = "BillPrintDeliveryCancel";	//发货取消接口
	/**
	 * 电子面单请求
	 * @param ediOrderList
	 * @param co
	 * @return
	 */
	public static List<BillPrintDetailRsp> mailNoRequest(EdiOrder ed,ExpressConfigure co,WarehouseAddress wha)throws ClientProtocolException, IOException {
		//获取报文
		String orderXml = createOrderInfo(ed,wha);
		try {
			//请求应答
			BillPrintResponse resp = new BillPrintResponse();
			//待签名
			String undigest = orderXml+co.getPassword();
			//生成签名
			String digest= Util.md5EncryptAndBase64(undigest);
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(co.getUrl());
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("serviceType", serviceType_Request));
			nvps.add(new BasicNameValuePair("parternID", co.getAccount()));
			nvps.add(new BasicNameValuePair("digest", digest));
			nvps.add(new BasicNameValuePair("msgId", ed.getOrdeno()));
			nvps.add(new BasicNameValuePair("bizData", orderXml));
			
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			String str = new String(EntityUtils.toString(entity));
			
			//响应的报文转成对象
			resp = JAXB.unmarshal(new StringReader(str), BillPrintResponse.class);
			List<BillPrintDetailRsp> billlst = resp.getBillPrintDetailRspList();
			if("SUCCESS".equals(resp.getResult())){
				log.info("=============请求汇通面单成功=================");
				return billlst;
			}else{
				log.info("=============请求汇通面单失败=================");
			}
			return null;
		} catch (ParseException e) {
			log.info("=============请求汇通面单失败=================");
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 创建订单
	 * @param ediOrderList
	 * @return
	 */
	private static String createOrderInfo(EdiOrder eo,WarehouseAddress wha){
		BillPrintRequest req = new BillPrintRequest();
		List<EDIPrintDetail> billList = new ArrayList<EDIPrintDetail>();
		EDIPrintDetail detail = new EDIPrintDetail();
		detail.setSendMan(wha.getContact());
		detail.setSendManPhone(wha.getMobile());
		detail.setSendManAddress(wha.getAddress());
		detail.setSendPostcode("");
		detail.setSendProvince(wha.getProvName());
		detail.setSendCity(wha.getCityName());
		detail.setSendCounty(wha.getDistName());
		detail.setReceiveMan(eo.getRecena());
		detail.setReceiveManPhone(eo.getTeleph());
		detail.setReceiveManAddress(eo.getAddres());
		detail.setReceivePostcode(eo.getPostco());
		detail.setReceiveProvince(eo.getProvna());
		detail.setReceiveCity(eo.getCityna());
		detail.setReceiveCounty(eo.getDistna());
		detail.setTxLogisticID(eo.getOrdeno());
		detail.setItemName("");
		detail.setItemWeight("");
		detail.setItemCount("");
		detail.setRemark(eo.getRemark());
		billList.add(detail);
		req.setDeliveryConfirm("false");
		req.setEDIPrintDetailList(billList);
		StringWriter writer = new StringWriter();
		JAXB.marshal(req,writer);
		return writer.toString();
	}
	/**
	 * 发货反馈
	 * @param eo
	 * @param co
	 * @return
	 */
	public static String deliveryRequestBack(EdiOrder eo,ExpressConfigure co,WarehouseAddress wha,String mailno) {
		//获取报文
		String orderXml = createOrderInfoBack(eo,wha,mailno);
		log.info("==============汇通发货反馈报文=================="+orderXml);
		try {
			//请求应答
			BillPrintDeliveryResponse resp = new BillPrintDeliveryResponse();
			//待签名
			String undigest = orderXml+co.getPassword();
			//生成签名
			String digest= Util.md5EncryptAndBase64(undigest);
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(co.getUrl());
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("serviceType", serviceType_Back));
			nvps.add(new BasicNameValuePair("parternID", co.getAccount()));
			nvps.add(new BasicNameValuePair("digest", digest));
			nvps.add(new BasicNameValuePair("msgId", eo.getOrdeno()));
			nvps.add(new BasicNameValuePair("bizData", orderXml));
			
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			String str = new String(EntityUtils.toString(entity));
			log.info("==============汇通发货反馈报文==================");
			log.info(str);
			//响应的报文转成对象
			resp = JAXB.unmarshal(new StringReader(str), BillPrintDeliveryResponse.class);
			if("SUCCESS".equals(resp.getResult())){
				log.info("==============发货反馈成功==================");
			}else{
				log.info("==============发货反馈失败==================");
				//add 20160607
                throw new SelfException("汇通发货反馈返回失败");
			}
		} catch (Exception e) {
            log.error("汇通发货反馈异常.", e);
            throw new RuntimeException(e);
        }
		return null;
	}
	/**
	 * 创建订单(反馈)
	 * @param ediOrderList
	 * @return
	 */
	private static String createOrderInfoBack(EdiOrder eo,WarehouseAddress wha,String mailno){
		BillPrintDeliveryRequest req = new BillPrintDeliveryRequest();
		List<CreatePrintFeedBack> backList = new ArrayList<CreatePrintFeedBack>();
		CreatePrintFeedBack back = new CreatePrintFeedBack();
		back.setSendMan(wha.getContact());
		back.setSendManPhone(wha.getMobile());
		back.setSendManAddress(wha.getAddress());
		back.setSendPostcode("");
		back.setSendProvince(wha.getProvName());
		back.setSendCity(wha.getCityName());
		back.setSendCounty(wha.getDistName());
		back.setReceiveMan(eo.getRecena());
		back.setReceiveManPhone(eo.getTeleph());
		back.setReceiveManAddress(eo.getAddres());
		back.setReceivePostcode(eo.getPostco());
		back.setReceiveProvince(eo.getProvna());
		back.setReceiveCity(eo.getCityna());
		back.setReceiveCounty(eo.getDistna());
		back.setTxLogisticID(eo.getOrdeno());
		back.setItemName("");
		back.setItemWeight("");
		back.setItemCount("");
		back.setRemark(eo.getRemark());
		back.setMailNo(mailno);
		backList.add(back);
		req.setBackList(backList);
		StringWriter writer = new StringWriter();
		JAXB.marshal(req,writer);
		return writer.toString();
	}
	/**
	 * 发货取消
	 * @param mailNo
	 * @param co
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void BillPrintDeliveryCancel(String mailNo,ExpressConfigure co) throws ClientProtocolException, IOException{
		try {
			BillCancelResponse resp = new BillCancelResponse();
			BillPrintDeliveryCancel cancel = new BillPrintDeliveryCancel();
			List<RemovePrintFeedBack> rbs = new ArrayList<RemovePrintFeedBack>();
			RemovePrintFeedBack rb = new RemovePrintFeedBack();
			rb.setMailNo(mailNo);
			rbs.add(rb);
			cancel.setRemovePrintFeedbackList(rbs);
			StringWriter writer = new StringWriter();
			JAXB.marshal(cancel,writer);
			String orderXml = writer.toString();
			log.info("==============汇通发货取消报文=================="+orderXml);
			//待签名
			String undigest = orderXml+co.getPassword();
			//生成签名
			String digest= Util.md5EncryptAndBase64(undigest);
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(co.getUrl());
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("serviceType", serviceType_Cancel));
			nvps.add(new BasicNameValuePair("parternID", co.getAccount()));
			nvps.add(new BasicNameValuePair("digest", digest));
			nvps.add(new BasicNameValuePair("msgId", mailNo));
			nvps.add(new BasicNameValuePair("bizData", writer.toString()));
			
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			String str = new String(EntityUtils.toString(entity));
			log.info("==============汇通发货取消报文==================");
			log.info(str);
			//响应的报文转成对象
			resp = JAXB.unmarshal(new StringReader(str), BillCancelResponse.class);
			if("SUCCESS".equals(resp.getResult())){
				log.info("==============发货取消成功==================");
			}else{
				log.info("==============发货取消失败==================");
			}
		} catch (ParseException e) {
			log.info("==============发货取消失败==================");
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws ClientProtocolException, IOException {
//		BillPrintDeliveryRequest resp = new BillPrintDeliveryRequest();
//		List<CreatePrintFeedBack> rsplist = new ArrayList<CreatePrintFeedBack>();
//		List<CreatePrintFeedBack> list = new ArrayList<CreatePrintFeedBack>();
//		CreatePrintFeedBack detail = new CreatePrintFeedBack();
//		detail.setSendMan("张三");
//		detail.setSendManPhone("1231231");
//		detail.setSendManAddress("广东省深圳市南山区");
//		detail.setSendPostcode("");
//		detail.setSendProvince("广东省");
//		detail.setSendCity("深圳市");
//		detail.setSendCounty("南山区");
//		detail.setReceiveMan("啦啦啦啦");
//		detail.setReceiveManPhone("23423423");
//		detail.setReceiveManAddress("上海市浦东新区唐镇");
//		detail.setReceivePostcode("");
//		detail.setReceiveProvince("");
//		detail.setReceiveCity("上海市");
//		detail.setReceiveCounty("浦东新区");
//		detail.setTxLogisticID("123456");
//		detail.setItemName("书");
//		detail.setItemWeight("10.0");
//		detail.setItemCount("1");
//		detail.setRemark("");
//		detail.setMailNo("50002759500679");
//		list.add(detail);
//		resp.setBackList(list);
//		StringWriter writer = new StringWriter();
//		JAXB.marshal(resp,writer);
//		System.out.println(writer.toString());
//		
//		BillPrintDeliveryCancel cancel = new BillPrintDeliveryCancel();
//		List<RemovePrintFeedBack> rbs = new ArrayList<RemovePrintFeedBack>();
//		RemovePrintFeedBack rb = new RemovePrintFeedBack();
//		rb.setMailNo("50002775109983");
//		rbs.add(rb);
//		StringWriter writer = new StringWriter();
//		JAXB.marshal(rbs,writer);
//		String data = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><BillCodeRequest><printSite>printSite</printSite><printMan>printMan</printMan></BillCodeRequest>";
//		String key = "DbFPPUbPMDYt";
//		String undigest = data+key;
//		System.out.println(undigest);
//		String base64xml= Util.md5EncryptAndBase64(undigest);
//		System.out.println(base64xml);
//		HttpClient httpclient = new DefaultHttpClient();
//		HttpPost httpPost = new HttpPost("http://ebill.ns.800best.com/ems/api/process");
//		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//		nvps.add(new BasicNameValuePair("serviceType", "BillCodeRequest"));
//		nvps.add(new BasicNameValuePair("parternID", "314200_0022"));
//		nvps.add(new BasicNameValuePair("digest", base64xml));
//		nvps.add(new BasicNameValuePair("msgId", "2"));
//		nvps.add(new BasicNameValuePair("bizData", data));
//		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
//		HttpResponse response = httpclient.execute(httpPost);
//		HttpEntity entity = response.getEntity();
//		String str = new String(EntityUtils.toString(entity));

//		System.out.println(str);
////	resp = JAXB.unmarshal(str, BillPrintResponse.class);
//		resp = JAXB.unmarshal(new StringReader(str), BillPrintResponse.class);
//		System.out.println("运单号"+resp.getBillPrintDetailRspList().get(0).getMailNo());
		
	}
}
